package com.ipet.system.controller;

import com.ipet.system.pojo.SysUser;
import com.ipet.system.service.SysUserService;
import com.ipet.utils.JWTUtils2;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/sysUser")
@Api("管理员模块")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;
    @ApiOperation(value = "登陆")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户名" , name = "username" , required = true , dataType = "String" , paramType = "query"),
            @ApiImplicitParam(value = "密码" , name = "password" , required = true , dataType = "String" , paramType = "query")
    })
    @PostMapping("/login")
    public ResponseEntity<Map<String , Object>> login(String username , String password){
        SysUser sysUser = sysUserService.findByUsername(username);
        HashMap<String, Object> map = new HashMap<>();
        if(sysUser == null){
            map.put("message" , "用户名错误!");
        }else {
            boolean checkpw = BCrypt.checkpw(password, sysUser.getPassword());
            if(checkpw){
                String token = JWTUtils2.generToken(sysUser.getId() + "", sysUser.getUsername(), "ipet");
                map.put("token" , token);
                map.put("message" ,sysUser.getUsername() + "欢迎登陆！");
                map.put("user" , sysUser);
            }else {
                map.put("message" , "密码错误！");
            }
        }
       return ResponseEntity.ok(map);
    }
    @ApiOperation(value = "更新或添加管理员")
    @ApiImplicitParam(value = "要更新或添加的管理员信息" , name = "sysUser" , required = true , dataType = "SysUser" , paramType = "body")
    @PostMapping("/saveOrUpdate")
    public ResponseEntity<Boolean> update(@RequestBody SysUser sysUser){
        String hashpw = BCrypt.hashpw(sysUser.getPassword(), BCrypt.gensalt());
        sysUser.setPassword(hashpw);
        boolean saveOrUpdate = sysUserService.saveOrUpdate(sysUser);
        return ResponseEntity.ok(saveOrUpdate);
    }

}
